<?php
class CategoriesController extends AppController {

	var $name = 'Categories';

	public function beforeFilter(){
		parent::beforeFilter();
		//		$this->layout = 'cms';
	}
	
	function index() {
		$this->Category->recursive = 0;
		$this->paginate = array('order'=>array("lft"=>"asc"));
		$categories = $this->treeForCombobox( $this->paginate(),'Category',true);
		$this->set('categories', $categories);
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid category', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('category', $this->Category->read(null, $id));
	}

	function add() {
		if (!empty($this->data)) {
			$this->Category->create();
			if ($this->Category->save($this->data)) {
				$this->Category->updateAll(
				array('Category.parent_id' => 0),
				array('Category.parent_id' => NULL)
				);
				$this->Session->setFlash(__('The category has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The category could not be saved. Please, try again.', true));
			}
		}
// 		$uploads = $this->Category->Upload->find('list');
// 		$items = $this->Category->Item->find('list');
		$this->Category->recursive = 0;
		$parentCategory = $this->Category->find('threaded');		
		$parentCategories = $this->treeForCombobox($parentCategory,'Category');
// 		$this->data['Category']['parent_id'] = (is_null($parent_id)) ? null : $parent_id;
		$this->set(compact('parentCategories'));
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid category', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Category->save($this->data)) {
				$this->Category->updateAll(
				array('Category.parent_id' => 0),
				array('Category.parent_id' => NULL)
				);
				$this->Session->setFlash(__('The category has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The category could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Category->read(null, $id);
		}
		$parentCategory = $this->Category->find('threaded', array());
		$parentCategories = $this->treeForCombobox($parentCategory,'Category');			
		$this->set(compact('parentCategories'));
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for category', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Category->delete($id)) {
			$this->Session->setFlash(__('Category deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Category was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}	
	
}
